package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.model.Item;
import meiyunting.shiwuzhaoling.model.ItemStatus;
import meiyunting.shiwuzhaoling.model.ItemType;
import meiyunting.shiwuzhaoling.service.ItemService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页控制器 - 展示按类型分类的物品
 */
@Controller
public class HomeController {

    private final ItemService itemService;

    public HomeController(ItemService itemService) {
        this.itemService = itemService;
    }

    /**
     * 首页 - 展示各类型的物品
     */
    @GetMapping("/")
    public String home(Model model) {
        // 获取并按类型分组物品
        Map<ItemType, List<Item>> itemsByType = new HashMap<>();
        
        for (ItemType type : ItemType.values()) {
            // 每种类型获取最多5个物品
            List<Item> items = itemService.getItemsByType(type);
            if (!items.isEmpty()) {
                // 如果有超过5个物品，只保留前5个
                if (items.size() > 5) {
                    items = items.subList(0, 5);
                }
                itemsByType.put(type, items);
            }
        }
        
        // 分别获取失物和招领的最新物品
        List<Item> lostItems = itemService.getItemsByStatus(ItemStatus.LOST);
        List<Item> foundItems = itemService.getItemsByStatus(ItemStatus.FOUND);
        
        // 只保留最新的5条
        if (lostItems.size() > 5) {
            lostItems = lostItems.subList(0, 5);
        }
        if (foundItems.size() > 5) {
            foundItems = foundItems.subList(0, 5);
        }
        
        model.addAttribute("itemsByType", itemsByType);
        model.addAttribute("lostItems", lostItems);
        model.addAttribute("foundItems", foundItems);
        model.addAttribute("itemTypes", ItemType.values());
        
        return "home";
    }
} 